package utils

import (
	"bytes"
	"encoding/base64"
	"fmt"
	"github.com/gogf/gf/frame/g"
	"github.com/xuri/excelize/v2"
	"io/fs"
	"io/ioutil"
	"math/rand"
	"net/http"
	"os"
	"path/filepath"
	"regexp"
	"strconv"
	"time"

	"github.com/gogf/gf/util/gconv"
)

func IsHttpHref(href string) bool {
	reg := regexp.MustCompile(`^http://|https://`)
	if reg.Match(gconv.Bytes(href)) {
		return true
	} else {
		return false
	}
}

func ReadExcel(dir string) ([]string, error) {
	f, err := excelize.OpenFile(dir)
	if err != nil {
		fmt.Println(err)
		return nil, err
	}

	// 获取 Sheet1 上所有的行
	rows, err := f.GetRows("Sheet1")
	if err != nil {
		fmt.Println(err)
		return nil, err
	}

	var result []string
	for _, row := range rows {
		for _, colCell := range row {
			fmt.Print(colCell, "\t")
		}
		result = append(result, row[0])

	}
	return result, nil
}

// 生成任务ID

func GenerateTaskID() string {
	rand.Seed(time.Now().UnixNano())
	str := "SD_TASK_ID_"
	return str + strconv.FormatInt(time.Now().UnixNano(), 10) + strconv.Itoa(rand.Intn(10000))
}

// 保存base64编码的图片

func SaveEncodedImage(b64Image string, outputPath string) error {
	decodedImage, err := base64.StdEncoding.DecodeString(b64Image)
	if err != nil {
		return err
	}

	err = ioutil.WriteFile(outputPath, decodedImage, 0644)
	if err != nil {
		return err
	}

	return nil
}

func WeekTime(title string) string {
	now := time.Now()
	weekStart := now.AddDate(0, 0, -int(now.Weekday())+1)
	weekEnd := weekStart.AddDate(0, 0, 6)
	weektime := fmt.Sprintf("%d.%02d.%02d-%d.%02d.%02d", weekStart.Year(), weekStart.Month(), weekStart.Day(), weekEnd.Year(), weekEnd.Month(), weekEnd.Day())
	driverPath := g.Cfg().GetString("download.path")
	isExist, path, err := CheckFileExist(driverPath, title)
	if isExist == true && err == nil {
		fmt.Println("文件夹已存在:", path)
		return path
	} else {
		fmt.Println("文件夹不存在：创建 文件夹")
		reg := regexp.MustCompile(`[\\/:*?"<>|]`)
		title = reg.ReplaceAllString(title, "_")
		folderName := filepath.Join(driverPath, weektime, title)
		// 创建文件夹
		err = os.MkdirAll(folderName, os.ModePerm)
		if err != nil {
			fmt.Println("创建文件夹失败:", err)
		}
		return folderName
	}

}

func RandomSleep() {
	time.Sleep(time.Duration(rand.Intn(5)+5) * time.Second)
}

func CheckFileExist(root string, fileName string) (bool, string, error) {
	// 遍历文件夹
	found := false
	cPath := ""
	err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
		if err != nil {
			return err
		}

		// 检查是否为指定名称的文件夹
		if d.Name() == fileName {
			found = true
			if err != nil {
				return err
			}
			//fmt.Println("path:", path)
			cPath = path
		}

		return nil
	})

	if err != nil {
		return false, cPath, err
	}

	return found, cPath, nil
}

func SubmitPost(url string, jsonData []byte) (*http.Response, error) {
	//jsonData, err := json.Marshal(data)
	//if err != nil {
	//	return nil, err
	//}
	//
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
	if err != nil {
		return nil, err
	}

	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("accept", "application/json")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}

	return resp, nil
}
